<template>
  <view class="container">
    <!-- 今日学习数据卡片 -->
    <view class="today-stats">
      <text class="section-title">今日学习</text>
      <view class="stats-grid">
        <view class="stat-card">
          <view class="stat-value">{{ todayStats.wordsLearned }}</view>
          <text class="stat-label">学习单词</text>
          <text class="stat-change" :class="{'positive': todayStats.wordsIncrease > 0}">
            {{ todayStats.wordsIncrease > 0 ? '+' : '' }}{{ todayStats.wordsIncrease }}
          </text>
        </view>
        <view class="stat-card">
          <view class="stat-value">{{ todayStats.correctRate }}%</view>
          <text class="stat-label">正确率</text>
          <text class="stat-change" :class="{'positive': todayStats.rateIncrease > 0}">
            {{ todayStats.rateIncrease > 0 ? '+' : '' }}{{ todayStats.rateIncrease.toFixed(1) }}%
          </text>
        </view>
        <view class="stat-card">
          <view class="stat-value">{{ formatTime(todayStats.studyTime) }}</view>
          <text class="stat-label">学习时长</text>
          <text class="stat-change positive">连续学习{{ todayStats.streakDays }}天</text>
        </view>
      </view>
    </view>

    <!-- 周数据图表 -->
    <view class="weekly-stats">
      <view class="chart-header">
        <text class="section-title">本周数据</text>
        <view class="chart-legend">
          <view class="legend-item">
            <view class="legend-color words"></view>
            <text>单词量</text>
          </view>
          <view class="legend-item">
            <view class="legend-color time"></view>
            <text>时长(分钟)</text>
          </view>
        </view>
      </view>

      <!-- 柱状图 -->
      <view class="bar-chart">
        <view
            class="chart-column"
            v-for="(day, index) in weeklyData"
            :key="index"
        >
          <view class="bars">
            <view
                class="bar words-bar"
                :style="{ height: (day.wordsLearned / maxWords * 100) + '%' }"
            >
              <text class="bar-value">{{ day.wordsLearned }}</text>
            </view>
            <view
                class="bar time-bar"
                :style="{ height: (day.studyTime / maxTime * 100) + '%' }"
            >
              <text class="bar-value">{{ Math.floor(day.studyTime / 60) }}</text>
            </view>
          </view>
          <text class="day-label">{{ day.label }}</text>
        </view>
      </view>
    </view>

    <!-- 学习详情 -->
    <view class="learning-details">
      <text class="section-title">学习详情</text>
      <view class="details-list">
        <view class="detail-item" v-for="(detail, index) in todayDetails" :key="index">
          <view class="detail-header">
            <text class="detail-time">{{ detail.time ? detail.time : "-" }}</text>
            <text class="detail-type">{{ detail.type }}</text>
          </view>
          <view class="detail-content">
            <view class="detail-stats">
              <view class="detail-stat">
                <text class="stat-number">{{ detail.wordsCount ? detail.wordsCount : 0 }}</text>
                <text class="stat-desc">学习单词</text>
              </view>
              <view class="detail-stat">
                <text class="stat-number">{{ detail.correctCount ? detail.correctCount : 0 }}</text>
                <text class="stat-desc">正确数量</text>
              </view>
              <view class="detail-stat">
                <text class="stat-number">{{ detail.duration ? detail.duration : 0 }}</text>
                <text class="stat-desc">用时</text>
              </view>
            </view>
            <view class="progress-bar">
              <view
                  class="progress-fill"
                  :style="{ width: (detail.correctRate? detail.correctRate: 0) + '%' }"
              ></view>
              <text class="progress-text">正确率 {{ detail.correctRate ? detail.correctRate : 0 }}%</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {api} from '@/utils/request.js'

export default {
  data() {
    return {
      todayStats: {
        wordsLearned: 0,
        wordsIncrease: 0,
        correctRate: 0,
        rateIncrease: 0,
        studyTime: 0, // 秒
        streakDays: 0
      },
      weeklyData: [],
      todayDetails: []
    }
  },
  computed: {
    maxWords() {
      console.log(777, Math.max(...this.weeklyData.map(day => day.wordsLearned)) || 1)

      return Math.max(...this.weeklyData.map(day => day.wordsLearned)) || 1
    },
    maxTime() {
      return Math.max(...this.weeklyData.map(day => day.studyTime)) || 1
    }
  },
  onShow() {
    this.fetchDailyStatistics()
    this.fetchTodayAndYesterdayStatistics()
    this.getStatisticsByModel()
  },
  methods: {
    formatTime(seconds) {
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      if (hours === 0) return `${minutes}分钟`
      return `${hours}小时${minutes}分钟`
    },
    async getStatisticsByModel() {
      this.todayDetails = []
      const res0 = await api.getStatisticsByModel(1)
      const res1 = await api.getStatisticsByModel(2)
      const res2 = await api.getStatisticsByModel(3)
      const res3 = await api.getStatisticsByModel(0)
      this.todayDetails.push(
          {
            time: res3.result?.createAt,
            type: "学习模式",
            wordsCount: res3.result?.errorWord + res3.result?.currentWord,
            correctCount: res3.result?.errorWord,
            duration: res3.result ? this.formatTime(res3.result?.studyTime) : 0,
            correctRate: (((res3.result?.currentWord / (res3.result?.errorWord + res3.result?.currentWord)) ? (res3.result?.currentWord / (res3.result?.errorWord + res3.result?.currentWord)) : 0) * 100).toFixed(1)
          },
          {
            time: res0.result?.createAt,
            type: "闯关模式",
            wordsCount: res0.result?.errorWord + res0.result?.currentWord,
            correctCount: res0.result?.errorWord,
            duration: res0.result ? this.formatTime(res0.result?.studyTime) : 0,
            correctRate: (((res0.result?.currentWord / (res0.result?.errorWord + res0.result?.currentWord)) ? (res0.result?.currentWord / (res0.result?.errorWord + res0.result?.currentWord)) : 0) * 100).toFixed(1)
          },
          {
            time: res1.result?.createAt,
            type: "随机模式",
            wordsCount: res1.result?.errorWord + res1.result?.currentWord,
            correctCount: res1.result?.errorWord,
            duration: res1.result ? this.formatTime(res1.result?.studyTime) : 0,
            correctRate: (((res1.result?.currentWord / (res1.result?.errorWord + res1.result?.currentWord)) ? (res1.result?.currentWord / (res1.result?.errorWord + res1.result?.currentWord)) : 0) * 100).toFixed(1)
          },
          {
            time: res2.result?.createAt,
            type: "测试模式",
            wordsCount: res2.result?.errorWord + res2.result?.currentWord,
            correctCount: res2.result?.errorWord,
            duration: res2.result ? this.formatTime(res2.result?.studyTime) : 0,
            correctRate: (((res2.result?.currentWord / (res2.result?.errorWord + res2.result?.currentWord)) ? (res2.result?.currentWord / (res2.result?.errorWord + res2.result?.currentWord)) : 0) * 100).toFixed(1)
          },
      )
    },
    // 获取今日和昨日统计数据
    async fetchTodayAndYesterdayStatistics() {
      try {
        // 获取今日数据
        const todayRes = await api.getTodayStatistics()

        // 获取昨日数据
        const yesterdayRes = await api.getYesterdayStatistics()

        if (todayRes.code === 200 && todayRes.result) {
          const todayData = todayRes.result
          let yesterdayData = null

          // 如果昨日数据获取成功
          if (yesterdayRes.code === 200 && yesterdayRes.result) {
            yesterdayData = yesterdayRes.result
          }

          // 更新今日统计数据，并计算增长率
          this.updateTodayStats(todayData, yesterdayData)
        } else {
          console.error('获取今日统计数据失败:', todayRes.message)
        }
      } catch (error) {
        console.error('获取统计数据出错:', error)
      }
    },

    // 获取每日统计数据
    async fetchDailyStatistics() {
      try {
        const res = await api.getDailyStatistics()
        if (res.code === 200) {
          this.processStatisticsData(res.result)
        } else {
          console.error('获取统计数据失败:', res.message)
        }
      } catch (error) {
        console.error('获取统计数据出错:', error)
      }
    },

    // 处理后端返回的统计数据
    processStatisticsData(data) {
      console.log('周数据:', data)
      if (!data || !data.length) return

      // 获取当前日期
      const today = new Date()

      // 初始化周数据
      const weekDays = ['一', '二', '三', '四', '五', '六', '日']
      this.weeklyData = weekDays.map(label => ({
        label,
        wordsLearned: 0,
        studyTime: 0,
        correctWord: 0,
        errorWord: 0
      }))

      // 处理每日数据
      data.forEach(item => {
        // 解析日期
        const itemDate = new Date(item.date)
        const itemDayOfWeek = itemDate.getDay() || 7 // 将周日的0转为7

        // 判断是否是本周数据
        const isCurrentWeek = this.isSameWeek(today, itemDate)

        if (isCurrentWeek) {
          const index = itemDayOfWeek - 1 // 转换为数组索引 (0-6)

          // 更新周数据
          if (index >= 0 && index < 7) {
            this.weeklyData[index].wordsLearned = (item.currentWord + item.errorWord) || 0
            this.weeklyData[index].studyTime = item.studyTime || 0
            this.weeklyData[index].correctWord = item.currentWord || 0
            this.weeklyData[index].errorWord = item.errorWord || 0
          }
        }
      })
      console.log(7898, this.weeklyData)
    },

    // 更新今日统计数据
    updateTodayStats(todayData, yesterdayData) {

      // 如果没有数据，保持默认值
      if (!todayData) return

      // 计算今日学习单词总数
      const learnWord = todayData.currentWord + todayData.errorWord

      const todayWordsLearned = learnWord || 0
      // 计算今日正确率
      const todayCorrectRate = learnWord > 0
          ? ((todayData.currentWord / learnWord) * 100).toFixed(1)
          : 0

      // 计算与昨天相比的增长率
      let wordsIncrease = 0
      let rateIncrease = 0

      if (yesterdayData) {
        const yesterdayLearnWord = yesterdayData.currentWord + yesterdayData.errorWord
        // 计算昨日学习单词总数
        const yesterdayWordsLearned = yesterdayLearnWord || 0

        // 计算昨日正确率
        const yesterdayCorrectRate = yesterdayLearnWord > 0
            ? Math.round((yesterdayData.currentWord / yesterdayLearnWord) * 100)
            : 0

        // 计算单词数量增长
        wordsIncrease = todayWordsLearned - yesterdayWordsLearned

        // 计算正确率增长
        rateIncrease = todayCorrectRate - yesterdayCorrectRate
      } else {
        wordsIncrease = todayWordsLearned
        rateIncrease = todayCorrectRate
      }

      this.todayStats = {
        wordsLearned: todayWordsLearned,
        wordsIncrease: wordsIncrease,
        correctRate: todayCorrectRate,
        rateIncrease: rateIncrease,
        studyTime: todayData.studyTime || 0,
        streakDays: 1 // 连续学习天数，可以在后端计算
      }
    },

    // 判断两个日期是否是同一周
    isSameWeek(date1, date2) {
      const oneDay = 24 * 60 * 60 * 1000
      const date1Copy = new Date(date1.getTime())
      const date2Copy = new Date(date2.getTime())

      // 将日期调整到周一
      const day1 = date1Copy.getDay() || 7
      const day2 = date2Copy.getDay() || 7

      date1Copy.setTime(date1Copy.getTime() - (day1 - 1) * oneDay)
      date2Copy.setTime(date2Copy.getTime() - (day2 - 1) * oneDay)

      // 比较年份和周数
      return date1Copy.getFullYear() === date2Copy.getFullYear() &&
          this.getWeekNumber(date1Copy) === this.getWeekNumber(date2Copy)
    },

    // 获取日期的周数
    getWeekNumber(date) {
      const firstDayOfYear = new Date(date.getFullYear(), 0, 1)
      const pastDaysOfYear = (date - firstDayOfYear) / 86400000
      return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7)
    },

    // 判断两个日期是否是同一天
    isSameDay(date1, date2) {
      return date1.getFullYear() === date2.getFullYear() &&
          date1.getMonth() === date2.getMonth() &&
          date1.getDate() === date2.getDate()
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f6f7ff 0%, #e9eeff 100%);
  padding: 40rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.today-stats {
  .section-title {
    font-size: 40rpx;
  }

  margin-bottom: 40rpx;

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;

    .stat-card {
      background: white;
      border-radius: 20rpx;
      padding: 30rpx 20rpx;
      text-align: center;
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

      .stat-value {
        font-size: 40rpx;
        font-weight: bold;
        color: #2196F3;
        margin-bottom: 10rpx;
      }

      .stat-label {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 10rpx;
        display: block;
      }

      .stat-change {
        font-size: 22rpx;
        color: #ff5252;

        &.positive {
          color: #4CAF50;
        }
      }
    }
  }
}

.weekly-stats {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .chart-legend {
      display: flex;
      gap: 20rpx;

      .legend-item {
        display: flex;
        align-items: center;

        .legend-color {
          width: 24rpx;
          height: 24rpx;
          border-radius: 6rpx;
          margin-right: 8rpx;

          &.words {
            background: #2196F3;
          }

          &.time {
            background: #4CAF50;
          }
        }

        text {
          font-size: 24rpx;
          color: #666;
        }
      }
    }
  }

  .bar-chart {
    height: 400rpx;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    padding: 20rpx 0;

    .chart-column {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      height: 100%;

      .bars {
        flex: 1;
        width: 100%;
        display: flex;
        justify-content: center;
        gap: 10rpx;
        align-items: flex-end;
        margin-bottom: 20rpx;

        .bar {
          width: 30rpx;
          position: relative;
          transition: height 0.3s ease;

          .bar-value {
            position: absolute;
            top: -40rpx;
            left: 50%;
            transform: translateX(-50%);
            font-size: 20rpx;
            color: #666;
          }

          &.words-bar {
            background: #2196F3;
            border-radius: 6rpx 6rpx 0 0;
          }

          &.time-bar {
            background: #4CAF50;
            border-radius: 6rpx 6rpx 0 0;
          }
        }
      }

      .day-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.learning-details {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  .details-list {
    .detail-item {
      border-bottom: 2rpx solid #f5f6fa;
      padding: 20rpx 0;

      &:last-child {
        border-bottom: none;
      }

      .detail-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20rpx;

        .detail-time {
          font-size: 28rpx;
          color: #333;
        }

        .detail-type {
          font-size: 24rpx;
          color: #2196F3;
          background: rgba(33, 150, 243, 0.1);
          padding: 4rpx 16rpx;
          border-radius: 20rpx;
        }
      }

      .detail-content {
        .detail-stats {
          display: flex;
          margin-bottom: 20rpx;

          .detail-stat {
            flex: 1;
            text-align: center;

            .stat-number {
              font-size: 32rpx;
              font-weight: bold;
              color: #333;
              margin-bottom: 6rpx;
              display: block;
            }

            .stat-desc {
              font-size: 24rpx;
              color: #666;
            }
          }
        }

        .progress-bar {
          height: 30rpx;
          background: #f5f6fa;
          border-radius: 15rpx;
          position: relative;
          overflow: hidden;

          .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #2196F3, #4CAF50);
            border-radius: 15rpx;
            transition: width 0.3s ease;
          }

          .progress-text {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 24rpx;
            color: #babbb8;
            text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
          }
        }
      }
    }
  }
}
</style> 